package com.whfp.coky.ble.utils

/**
 *
 * 16进制处理
 * created by coky on 2022/4/9
 */
class HexToolKt {
    companion object{
        private val CODE:Array<String> = arrayOf("1", "2", "3","4", "5",
    "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")

        /**
         * @code 为16进制的String Code
         * @codeLength 额定指令长度
         * 指令补零加校验位
         */
        fun fillEndandSum(code:String,codeLength :Int = 20):String{
            val tailLength = codeLength*2-2-code.length
            var codeNew = code
            if (tailLength > 0){
                for (index in 1..tailLength step 2){
                    codeNew +="00"

                }
            }
            return fillSum(codeNew)
        }

//      加校验位
        private fun fillSum(code:String):String{
            var sum = 0
            for (index in 0..code.length step 2){
                sum +=hexString2Int(code.substring(index,index+2))
            }
            return code+int2HexString(sum%256)
        }

//-------------------------------base------------------------------------------
        /**
         * Int-->String
         * 10-->“0A”
         * 2位16进制数字,转16进制字符串
         */
        fun int2HexString(num:Int):String{
//            val high:Int =num shr 4
//            val low:Int = num and 0x0f
//            return (CODE[high] + CODE[low])
            return String.format("%2s",Integer.toHexString(num)).replace(" ","0")
        }

        /**
         * String-->Int
         * “0A”-->10
         * 16进制字符串转数字
         */
        fun hexString2Int(str: String):Int = Integer.parseInt(str,16)

        /**
         * String-->hexStr
         * “10”-->“0A”
         * 字符串转16进制字符
         */
        fun str2HexStr(str:String):String{
            val chars = "0123456789ABCDEF".toCharArray()
            val sb = StringBuilder("")
            val bs = str.toByteArray()
            var bit: Int
            for (i in bs.indices) {
                bit = (bs[i].toInt() and 0x0f0) shr 4
                sb.append(chars[bit])
                bit = bs[i].toInt() and 0x0f
                sb.append(chars[bit])
                // sb.append(' ');
            }
            return sb.toString().trim { it <= ' ' }
        }

        /**
         * hexStr-->String
         * “0A”-->“10”
         * 16进制字符串转字符
         */
        fun hexStr2Str(hexStr:String):String{
            val baKeyword = ByteArray(hexStr.length / 2)
            for (i in baKeyword.indices) {
                try {
                    baKeyword[i] = (0xff and hexStr.substring(i * 2, i * 2 + 2).toInt(16)).toByte()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            return String(baKeyword, charset("UTF-8"))
        }
    }
}